<template>
  <el-dialog title="添加风险单元" top="0vh" :visible.sync="visible" width="50%" :before-close="handleClose">
    <el-form :model="ruleForm" ref="ruleForm" :rules="rules" label-position="right">
      <el-form-item label="风险分析单元名称" :label-width="formLabelWidth" prop="riskUnitName">
        <el-input v-model="ruleForm.riskUnitName" placeholder="请输入风险分析单元名称" style="width:90%;" />
      </el-form-item>
      
      <el-form-item label="风险分析对象" :label-width="formLabelWidth" prop="oId">
        <el-select 
          v-model="ruleForm.oId" 
          placeholder="请选择风险分析对象" 
          ref="objectSelect"
          style="width:90%;"
          @change="handleObjectChange"
        >
          <el-option v-for="item in objectList" :key="item.oId" :label="item.oName" :value="item.oId" />
        </el-select>
      </el-form-item>

      <el-form-item label="责任部门" :label-width="formLabelWidth" prop="hazardDep">
        <el-input 
          v-model="ruleForm.hazardDep" 
          placeholder="请选择责任部门" 
          readonly 
          style="width:90%;"
          @click.native="chooseUnit('hazardDep')"
        />
      </el-form-item>

      <el-form-item label="责任人" :label-width="formLabelWidth" prop="hazardLiablePerson">
        <el-input 
          v-model="ruleForm.hazardLiablePerson" 
          placeholder="请选择责任人" 
          readonly
          style="width:90%;" 
          @click.native="choosePersonnel('hazardLiablePerson', {multiple: false})"
        />
      </el-form-item>

      <el-form-item label="是否停运" :label-width="formLabelWidth" prop="ifStop">
        <el-radio-group v-model="ruleForm.ifStop">
          <el-radio label="0">正常</el-radio>
          <el-radio label="1">停运</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    
    <el-dialog
      title="选择部门信息"
      top="12vh"
      :modal="false"
      :visible.sync="dialogFormVisibleUnit"
      width="30%"
      :before-close="handleDialogClose"
      append-to-body
    >
      <companyTree 
        :key="timerUnit" 
        @setCheckedList="getCheckedUintList" 
        :echoCheckedLabel="echoCheckedUnitLabel"
      ></companyTree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleUnit = false">取 消</el-button>
        <el-button type="primary" @click="confirmUnit">确 定</el-button>
      </span>
    </el-dialog>

    <el-drawer 
      title="人员选择" 
      :visible.sync="dialogFormVisiblePersonnel" 
      :modal="false" 
      size="50%" 
      :with-header="false"
    >
      <personnelSelection
        :multiple="multiple"
        @setCheckedList="getCheckedPersonnelList"
        :key="timerPersonnel"
        :echoCheckedLabel="echoCheckedLabel"
      >
      </personnelSelection>
    </el-drawer>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="submitForm('ruleForm')" :disabled="!buttonEnabled">
        {{ buttonEnabled ? '确 定' : '添加中...' }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { useRiskUnitApi } from '@/api/riskUnitApi';
import { useriskObjectApi } from '@/api/riskObjectApi';
import companyTree from "@/components/companyTree/index.vue";
import personnelSelection from '@/components/personnelSelection';

export default {
  name: 'AddAnalysis',
  components: {
    companyTree,
    personnelSelection
  },
  data() {
    return {
      visible: false,
      formLabelWidth: '150px',
      buttonEnabled: true,
      objectList: [],
      ruleForm: {
        riskUnitName: '',
        oId: '',
        hazardDep: '',
        hazardDepId: '',
        hazardLiablePerson: '',
        hazardLiablePersonId: '',
        ifStop: '0',
      },
      rules: {
        riskUnitName: [{ required: true, message: '请输入风险分析单元名称', trigger: 'blur' }],
        oId: [{ required: true, message: '请选择风险分析对象', trigger: 'change' }],
        hazardDep: [{ required: true, message: '请选择责任部门', trigger: 'change' }],
        hazardLiablePerson: [{ required: true, message: '请选择责任人', trigger: 'change' }],
        ifStop: [{ required: true, message: '请选择是否停运', trigger: 'change' }]
      },
      dialogFormVisibleUnit: false,
      echoCheckedUnitLabel: [],
      timerUnit: null,
      unitType: '',
      unitIdStr: '',
      unitNameStr: '',
      dialogFormVisiblePersonnel: false,
      multiple: false,
      timerPersonnel: null,
      PersonnelType: '',
      PersonnelIdStr: '',
      PersonnelNameStr: '',
      echoCheckedLabel: []
    }
  },
  methods: {
    show() {
      this.visible = true;
      this.getObjectList();
    },
    getObjectList() {
      useriskObjectApi().findObject().then(res => {
        if (res.code * 1 === 100) {
          this.objectList = res.info.records || [];
        }
      });
    },
    handleClose() {
      this.buttonEnabled = true;
      this.$refs.ruleForm?.resetFields();
      this.ruleForm = {
        riskUnitName: '',
        oId: '',
        hazardDep: '',
        hazardDepId: '',
        hazardLiablePerson: '',
        hazardLiablePersonId: '',
        ifStop: '0',
      };
      this.visible = false;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.buttonEnabled = false;
          useRiskUnitApi().addUnit(this.ruleForm).then(res => {
            if (res.code * 1 === 100) {
              this.$message.success('添加成功');
              this.$emit('success');
              this.handleClose();
              setTimeout(() => {
                this.buttonEnabled = true;
              }, 500);
            } else {
              this.$message.error(res.message || '添加失败');
              this.buttonEnabled = true;
            }
          }).catch(err => {
            console.error('添加失败:', err);
            this.$message.error('添加失败，请稍后重试');
            this.buttonEnabled = true;
          });
        } else {
          return false;
        }
      });
    },
    chooseUnit(value) {
      this.timerUnit = new Date().getTime();
      this.dialogFormVisibleUnit = true;
      this.unitType = value;
      this.echoCheckedUnitLabel = this.ruleForm[value] ? this.ruleForm[value].split(",") : [];
    },
    confirmUnit() {
      const nameKey = this.unitType;
      const idKey = `${nameKey}Id`;
      
      this.$set(this.ruleForm, nameKey, this.unitNameStr);
      this.$set(this.ruleForm, idKey, this.unitIdStr);
      this.dialogFormVisibleUnit = false;
    },
    getCheckedUintList(list) {
      this.unitIdStr = list.map((i) => i.id).join(',');
      this.unitNameStr = list.map((i) => i.label).join(',');
    },
    handleDialogClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    choosePersonnel(type, field) {
      this.PersonnelType = type;
      this.multiple = field.multiple;
      this.timerPersonnel = new Date().getTime();
      this.dialogFormVisiblePersonnel = true;
      this.echoCheckedLabel = this.ruleForm[type] ? this.ruleForm[type].split(',') : [];
    },
    getCheckedPersonnelList(list) {
      this.PersonnelIdStr = list.map((i) => i.id).join(',');
      this.PersonnelNameStr = list.map((i) => i.name).join(',');
      this.personConfirm();
    },
    personConfirm() {
      const nameKey = this.PersonnelType;
      const idKey = `${nameKey}Id`;
      
      this.$set(this.ruleForm, nameKey, this.PersonnelNameStr);
      this.$set(this.ruleForm, idKey, this.PersonnelIdStr);
      this.dialogFormVisiblePersonnel = false;
    },
    handleObjectChange() {
      this.$nextTick(() => {
        // 通过ref直接获取选中项的名称
        const selectedOption = this.$refs.objectSelect.selected;
        this.ruleForm.oName = selectedOption ? selectedOption.label : '';
      })
      
    }
  }
}
</script> 